<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import type { UnwrapRef } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
const assessmentName = ref<any>();
const columns = ref<any[]>([]);
const oldData = ref<any[]>([]);
const header = ref<any[]>([]);
const data = ref<any[]>([]);
const allData = ref<any[]>([]);
const loading = ref<boolean>(false);
async function getData() {
  loading.value = true;
  await getQuarterBySheetName(assessmentName.value).then((res: any) => {
    oldData.value = res.data;
  }).catch(() => {
    message.error('数据获取失败！');
  }).finally(() => {
    loading.value = false;
  });
  // 处理数据
  for (let i = 0; i < oldData.value.length; i++) {
    if (oldData.value[i].isField === 'true') {
      const headerdata = Object.keys(oldData.value[i])
        .filter(key => (key.startsWith('generalField') || key.startsWith('isField') || key.startsWith('id')) && oldData.value[i][key] !== '')
        .reduce((acc: any, key) => {
          acc[key] = oldData.value[i][key];
          return acc;
        }, {});
      header.value.push(headerdata);
      allData.value.push(headerdata);
    }
    else {
      const dataitem = Object.keys(oldData.value[i])
        .filter(key => (key.startsWith('generalField') || key.startsWith('isField') || key.startsWith('id')) && oldData.value[i][key] !== '')
        .reduce((acc: any, key) => {
          acc[key] = oldData.value[i][key];
          return acc;
        }, {});
      data.value.push(dataitem);
      allData.value.push(dataitem);
    }
  }
  loading.value = false;
}
function getColumns() {
  loading.value = true;
  const oldheader = ['generalFieldA', 'generalFieldB', 'generalFieldC', 'generalFieldD', 'generalFieldE', 'generalFieldF', 'generalFieldG', 'generalFieldH', 'generalFieldI', 'generalFieldJ', 'generalFieldK', 'generalFieldL', 'generalFieldM', 'generalFieldN', 'generalFieldO'];
  const header1 = header.value[0];
  const hlength = Object.keys(header1).length;
  for (let i = 0; i < hlength - 2; i++) {
    columns.value.push({
      dataIndex: oldheader[i],
      align: 'center',
    });
  }
  columns.value.push({
    dataIndex: 'operation',
    align: 'center',
    width: 150,
  });
  loading.value = false;
}
const lastSpan = ref<string>('');
const score = ref<any[]>([]);
const sData = ref<any[]>([]);
async function getScore() {
  lastSpan.value = '';
  score.value = [];
  sData.value = [];
  // 获取分数
  loading.value = true;
  await getQuarterBySheetName(assessmentName.value).then((res: any) => {
    sData.value = res.data;
    for (const key in sData.value[0]) {
      if (Object.prototype.hasOwnProperty.call(sData.value[0], key) && sData.value[0][key] !== '') {
        lastSpan.value = key;
      }
    }
    // 获取数据
    for (let i = 0; i < sData.value.length; i++) {
      if (sData.value[i].isField === 'false') {
        if (lastSpan.value) {
          const scoredata = {
            company: sData.value[i].generalFieldA,
            score: sData.value[i][lastSpan.value],
          };
          score.value.push(scoredata);
        }
      }
    }
  }).catch(() => {
    message.error('数据获取失败！');
  }).finally(() => {
    loading.value = false;
  });
}

onMounted(async () => {
  assessmentName.value = route.query.assessmentName;
  await getData();
  getColumns();
  getScore();
});

// 编辑
const editableData: UnwrapRef<Record<string, any>> = reactive({});
function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: { id: number }) => id === item.id)[0]);
}

async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: { id: number }) => id === item.id)[0], editableData[id]);

  const updateDate = {
    ...newData,
    sheetName: assessmentName.value,
  };
  await updateQuarterPublicSheet(updateDate).then(() => {
    message.success('编辑成功！');
    getData();
  }).catch(() => {
    message.error('编辑失败！');
  });

  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}
function deleteNum(newData: any) {
  const numberRegex = /^-?\d+(\.\d+)?$/;
  for (const key in newData) {
    if (Object.prototype.hasOwnProperty.call(newData, key)) {
      if (key !== 'id' && key !== 'isField' && key !== 'sheetName') {
        if (numberRegex.test(newData[key])) {
          newData[key] = '';
        }
      }
    }
  }
}
async function deletesummary(id: number) {
  const newData = ref<any>();
  await getQuarterPublicSheetById(id).then((res: any) => {
    newData.value = res.data;
  });
  deleteNum(newData.value);
  await updateQuarterPublicSheet(newData.value).then(() => {
    message.success('删除数据成功！');
    getData();
  }).catch(() => {
    message.error('删除数据失败！');
  });
}

async function onDelete(id: number) {
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: { id: number }) => item.id !== id);
      deletesummary(id);
    },
  });
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            {{ assessmentName }}
          </div>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button type="primary" @click="$router.push('/assessment_indicators/quarter/summary')">
            返回
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-table
        :columns="columns" :data-source="oldData" row-key="id" :scroll="{ x: 1200 }" class="q-table" bordered
        :loading="loading" :show-header="false" :pagination="false"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column?.dataIndex === 'operation' && record.isField === 'false'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.id]">
                <a-typography-link @click="save(record.id)">保存</a-typography-link>
                <a @click="cancel(record.id)">取消</a>
              </span>
              <span v-else>
                <a-space>
                  <a @click="edit(record.id)">编辑</a>
                  <a v-if="data.length" @click="onDelete(record.id)">删除</a>
                </a-space>
              </span>
            </div>
          </template>
          <template v-else-if="record.isField === 'true'">
            <div class="table-title">
              <p>{{ text }}</p>
            </div>
          </template>
          <template v-else>
            <div>
              <a-input
                v-if="editableData[record.id]"
                v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .m-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }

    .table-title {
      width: 100%;
      height: 100%;
      font-weight: bold;
    }
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
